package org.finesys.chat.core.base.embedding.filter.compairson;

import java.util.Objects;

import org.finesys.chat.core.base.document.Metadata;
import org.finesys.chat.core.base.embedding.filter.Filter;
import org.finesys.common.core.util.ValidationUtil;

public class GreaterThanEqualFilter implements Filter {

    private String key;
    private Comparable<?> comparisonValue;

    public GreaterThanEqualFilter(String key, Object compairsonValue) {
        this.key = ValidationUtil.ensureNotBlank(key, "key");
        this.comparisonValue = ValidationUtil.ensureNotNull(key, "comparisonValue");
    }

    public String getKey() {
        return key;
    }

    public Comparable<?> getCompairsonValue() {
        return comparisonValue;
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean test(Object object) {
        if (object instanceof Metadata) {
            Metadata metadata = (Metadata) object;
            if (!metadata.containsKey(this.key)) {
                return false;
            }
            Object actualValue = metadata.get(this.key);
            TypeChecker.ensureTypesAreCompatible(actualValue, this.comparisonValue, this.key);
            if (actualValue instanceof Number) {
                return NumberComparator.compareAsBigDecimals((Number) actualValue, this.comparisonValue) >= 0;
            } else {
                return ((Comparable) actualValue).compareTo(this.comparisonValue) >= 0;
            }
        }
        return false;
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) return true;
        if (object == null || getClass() != object.getClass()) return false;
        GreaterThanEqualFilter that = (GreaterThanEqualFilter) object;
        return Objects.equals(key, that.key) && Objects.equals(comparisonValue, that.comparisonValue);
    }

    @Override
    public int hashCode() {
        return Objects.hash(key, comparisonValue);
    }

    @Override
    public String toString() {
        return "GreaterThanEqualFilter{" +
                "key='" + key + '\'' +
                ", comparisonValue=" + comparisonValue +
                '}';
    }
}
